package com.bilin.coin.widget;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.R;
import com.bilin.coin.common.adapter.CommonAdapter;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;



public abstract class AbsPullToRefreshRecycleView<T> implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    protected View rootView;
    protected BaseAppCompatActivity activity;

    public RecyclerView recyclerView;
    protected SwipeRefreshLayout swipeRefresh;
    protected int page = 1;
    protected int pageSize = 0;
    protected int totalCount;
    protected int totalPageSize;
    protected List<T> dataList = new ArrayList<>();
    protected CommonAdapter adapter;
    protected boolean isRefresh = false;
    protected boolean enableRefresh = true;
    protected boolean enableLoadFirst = true;//第一次是否加载
    protected boolean enableLoadMore = true;//能否加载更多
    protected boolean isPostJson = false;//是否以json格式传参

    public View getRootView() {
        return rootView;
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity) {
        this.activity = activity;
        init();
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity, boolean enableRefresh) {
        this.activity = activity;
        this.enableRefresh = enableRefresh;
        init();
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity, boolean enableRefresh, boolean enableLoadFirst) {
        this.activity = activity;
        this.enableRefresh = enableRefresh;
        this.enableLoadFirst = enableLoadFirst;
        init();
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity, boolean enableRefresh, boolean enableLoadFirst, boolean enableLoadMore) {
        this.activity = activity;
        this.enableRefresh = enableRefresh;
        this.enableLoadFirst = enableLoadFirst;
        this.enableLoadMore = enableLoadMore;
        init();
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity,RecyclerView recyclerView, boolean enableRefresh, boolean enableLoadFirst, boolean enableLoadMore) {
        this.activity = activity;
        this.recyclerView = recyclerView;
        this.enableRefresh = enableRefresh;
        this.enableLoadFirst = enableLoadFirst;
        this.enableLoadMore = enableLoadMore;
        this.isPostJson = isPostJson;
        init();
    }

    public AbsPullToRefreshRecycleView(BaseAppCompatActivity activity,RecyclerView recyclerView, boolean enableRefresh, boolean enableLoadFirst, boolean enableLoadMore,boolean isPostJson) {
        this.activity = activity;
        this.recyclerView = recyclerView;
        this.enableRefresh = enableRefresh;
        this.enableLoadFirst = enableLoadFirst;
        this.enableLoadMore = enableLoadMore;
        this.isPostJson = isPostJson;
        init();
    }

    public abstract int fillPageSize();

    public abstract boolean isPost();

    private void init() {
        rootView = View.inflate(activity, R.layout.public_no_toolbar_recyclerview, null);
        if (recyclerView == null) {
            recyclerView = rootView.findViewById(R.id.rv_public_recyclerview);
            swipeRefresh = rootView.findViewById(R.id.swipeRefresh);
            swipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.green_1, R.color.red_btn_bg_color, R.color.black999);
            if (!enableRefresh) swipeRefresh.setEnabled(false);
        } else {
            rootView = recyclerView;
        }
        initAdapter();
        //swipeRefresh.setRefreshing(true);
        pageSize = fillPageSize();
        if (enableLoadFirst) {
            if (!isPostJson) {
                getDataList();
            } else {
                getDataList2();
            }
        }
    }

    private void getDataList2() {
        if(isPost()) {
            RequestUtils
                    .postJson("{\"pageNumber\":"+page+",\"pageSize\":"+pageSize+"}", ApiConstant.BaseInnerUrl)
                    .url(fillUrl())
                    .build()
                    .compose(activity.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                adapter.setNewData(data);
                                if (onMyRefreshListener != null) {
                                    onMyRefreshListener.OnMyRefresh();
                                }
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                if (isShowEmptyView()) {
                                    adapter.setEmptyView(fillEmptyView());
                                }
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                adapter.disableLoadMoreIfNotFullPage();
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            refreshViewDone();
                            activity.showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        } else {
            RequestUtils
                    .get()
                    .url(fillUrl())
                    /* .addParams("pageNum", page+"")
                     .addParams("pageSize", pageSize+"")*/
                    .params(fillParams())
                    .build()
                    .compose(activity.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                if (onMyRefreshListener != null) {
                                    onMyRefreshListener.OnMyRefresh();
                                }
                                adapter.setNewData(data);
                                if (onFillDataFinishListener != null) {
                                    onFillDataFinishListener.OnFillDataFinish();
                                }
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                if (isShowEmptyView()) {
                                    adapter.setEmptyView(fillEmptyView());
                                }
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                if (enableLoadMore) {
                                    adapter.disableLoadMoreIfNotFullPage();
                                }
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            refreshViewDone();
                            activity.showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        }
    }

    private void refreshViewDone() {
        if (swipeRefresh != null) swipeRefresh.setRefreshing(false);
    }

    private void getDataList() {
        if(isPost()) {
            RequestUtils
                    .post()
                    .url(fillUrl())
                    .build()
                    .compose(activity.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                adapter.setNewData(data);
                                if (onMyRefreshListener != null) {
                                    onMyRefreshListener.OnMyRefresh();
                                }
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                if (isShowEmptyView()) {
                                    adapter.setEmptyView(fillEmptyView());
                                }
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                adapter.disableLoadMoreIfNotFullPage();
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            refreshViewDone();
                            activity.showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        } else {
            RequestUtils
                    .get()
                    .url(fillUrl())
                    /* .addParams("pageNum", page+"")
                     .addParams("pageSize", pageSize+"")*/
                    .params(fillParams())
                    .build()
                    .compose(activity.<String>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new CommonCallBack() {
                        @Override
                        protected void onError(String errorMsg) {
                            error(errorMsg);
                        }
                        @Override
                        protected void onSuccess(String dataJson) {
                            List<T> data = parseListDataAndFillTotal(dataJson);
                            totalPageSize = totalCount / pageSize;
                            if (totalCount % pageSize > 0) {
                                totalPageSize += 1;
                            }
                            if (isRefresh) {
                                page = 1;
                                if (onMyRefreshListener != null) {
                                    onMyRefreshListener.OnMyRefresh();
                                }
                                adapter.setNewData(data);
                                if (onFillDataFinishListener != null) {
                                    onFillDataFinishListener.OnFillDataFinish();
                                }
                            } else {
                                adapter.addData(data);
                            }
                            if (data.size() <= 0) {
                                //adapter.setEmptyView(R.layout.empty_view_no_data, (ViewGroup) recyclerView.getParent());
                                if (isShowEmptyView()) {
                                    adapter.setEmptyView(fillEmptyView());
                                }
                            }
                            if (totalCount < minSize()) {
                                //去掉第一次进入页面进行底部刷新
                                if (enableLoadMore) {
                                    adapter.disableLoadMoreIfNotFullPage();
                                }
                            } else {
                                adapter.loadMoreComplete();
                            }
                            page++;
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onCallBackError(Throwable e) {
                            adapter.loadMoreFail();
                            refreshViewDone();
                            activity.showMsg(e);
                            DialogUtils.dismissDialogLoading();
                        }

                        @Override
                        protected void onStopRefresh() {
                            refreshViewDone();
                            DialogUtils.dismissDialogLoading();
                        }
                    });
        }
    }

    protected boolean isShowEmptyView() {
        return true;
    }

    private OnMyRefreshListener onMyRefreshListener;
    private OnFillDataFinishListener onFillDataFinishListener;
    public interface OnMyRefreshListener {
        void OnMyRefresh();
    }
    public interface OnFillDataFinishListener {
        void OnFillDataFinish();
    }

    public OnFillDataFinishListener getOnFillDataFinishListener() {
        return onFillDataFinishListener;
    }

    public void setOnFillDataFinishListener(OnFillDataFinishListener onFillDataFinishListener) {
        this.onFillDataFinishListener = onFillDataFinishListener;
    }

    public OnMyRefreshListener getOnMyRefreshListener() {
        return onMyRefreshListener;
    }

    public void setOnMyRefreshListener(OnMyRefreshListener onMyRefreshListener) {
        this.onMyRefreshListener = onMyRefreshListener;
    }


    private void error(String errorMsg) {
        activity.showToast(errorMsg);
        if (swipeRefresh != null)
            swipeRefresh.setRefreshing(false);
        DialogUtils.dismissDialogLoading();
    }

    public abstract List<T> parseListDataAndFillTotal(String dataJson);

    public abstract Map<String, String> fillParams();

    public int minSize() {
        return 10;
    }

    public abstract String fillUrl();

    private void initAdapter() {
        if (swipeRefresh != null) {
            swipeRefresh.setOnRefreshListener(this);
        }
        adapter = createAdapter();
        adapter.openLoadAnimation(fillAnimationType());
        adapter.setNotDoAnimationCount(4);
        recyclerView.setLayoutManager(fillLayoutManger());
        if (enableLoadMore) {
            adapter.setOnLoadMoreListener(this, recyclerView);
            adapter.disableLoadMoreIfNotFullPage();
        }
        if (isShowEmptyView()) {
            adapter.setEmptyView(fillEmptyView());
        }
        recyclerView.setAdapter(adapter);
    }

    protected int fillAnimationType() {
        return BaseQuickAdapter.SLIDEIN_BOTTOM;
    }

    public CommonAdapter getAdapter() {
        return adapter;
    }

    protected View fillEmptyView() {
        return View.inflate(activity,R.layout.empty_view_no_data,null);
    }

    protected RecyclerView.LayoutManager fillLayoutManger() {
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(RecyclerView.VERTICAL);
        DividerItemDecoration decor = new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
        decor.setDrawable(ContextCompat.getDrawable(activity,R.drawable.custom_divider));
        recyclerView.addItemDecoration(decor);
        return manager;
    }
    private CommonAdapter<T> createAdapter() {
        CommonAdapter commonAdapter = new CommonAdapter<T>(fillItemLayout(), dataList) {
            @Override
            protected void convert(BaseViewHolder helper, T item) {
                convertItem(helper,item);
            }

            @Override
            public void onViewRecycled(@NonNull BaseViewHolder holder) {
                super.onViewRecycled(holder);
                onViewRecycledMy(holder);
            }
        };
        return commonAdapter;
    }

    protected void onViewRecycledMy(BaseViewHolder holder) {

    }

    protected abstract void convertItem(BaseViewHolder helper, T item);

    protected abstract int fillItemLayout();

    @Override
    public void onLoadMoreRequested() {
        if (page > totalPageSize) {
            adapter.loadMoreEnd(false);
        } else {
            refresh(false);
        }
    }
    @Override
    public void onRefresh() {
        refresh(true);
    }
    public void refresh(boolean isRefresh) {
        //adapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        this.isRefresh = isRefresh;
        if (isRefresh) {
            page = 1;
            pageSize = fillPageSize();
        }
        if (!isPostJson) {
            getDataList();
        } else {
            getDataList2();
        }
    }
}
